//
//  PPYLoginView.swift
//  PanPanYan
//
//  Created by 向攀 on 2017/11/29.
//  Copyright © 2017年 向攀. All rights reserved.
//

import UIKit
import RxSwift
import RxCocoa
//import SnapKit
import MBProgressHUD


@objc
protocol PPYLoginViewDelegate: NSObjectProtocol {
    @objc optional func getVerifyButtonClicked(mobilePhone: String)
    @objc optional func loginButtonClicked(mobilePhone: String, verifyCode: String)
}

class PPYLoginView: UIView {
    
    weak var delegate:PPYLoginViewDelegate?
    
    fileprivate let disposeBag = DisposeBag()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
        setupRxSwift()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupUI() -> Void {
        setupMobilePhoneTextField()
        setupVerifyCodeTextField()
        addSubview(loginButton)
        
//        loginButton.frame = CGRect(x: 40, y: 160, width: self.bounds.size.width - 80, height: 45)
        loginButton.snp.makeConstraints { (make) in
            make.top.equalTo(verifyCodeTextField.snp.bottom).offset(52)
            make.left.right.equalTo(verifyCodeTextField.superview!)
            make.height.equalTo(45)
        }
    }
    
    func setupRxSwift() -> Void {
//        let mobilePhone = mobilePhoneTextField.rx.text.orEmpty.throttle(0.3, scheduler: MainScheduler.instance)
//        mobilePhoneTextField.rx.text.orEmpty.asObservable().subscribe({ (event) in
//            print(event)
//        })

//        _ = mobilePhoneTextField.rx.text.orEmpty.asObservable().subscribe { [weak self] (event) in
//
//            guard let weakSelf = self else {
//                return
//            }
//            print("--------------------")
//            print(event)
////            getVerifyCodeButton.isUserInteractionEnabled =
//            print(type(of: event))
//            let testt = event.element
//            print(testt as Any)
//            if testt == "" {
//                print("--xfjklgjs--")
//            }
//            weakSelf.getVerifyCodeButton.isUserInteractionEnabled = testt != nil
//        }
        
        mobilePhoneTextField.rx.text.orEmpty.asObservable() //信号封装
        .map { (text) -> Bool in //信号处理
            return text.count > 10
        }
        .bind(to: getVerifyCodeButton.rx.isEnabled) //信号绑定,类似订阅
        .disposed(by: disposeBag) //信号释放,类似于一个ARC的自动垃圾回收机制

        Observable.combineLatest(mobilePhoneTextField.rx.text.orEmpty, verifyCodeTextField.rx.text.orEmpty) { (text1: String, text2: String) -> Bool in
            return (text1.count > 10 && text2.count > 3)
        }
        .bind(to: loginButton.rx.isEnabled)
        .disposed(by: disposeBag)
        
//        mobilePhoneTextField.rx.text.orEmpty.asObservable().subscribe {
//            print("--------------------")
//            print($0)
//        }

//        mobilePhoneTextField.rx.text.orEmpty.asObservable().bind(to: <#T##Variable<String>#>)

//            .distinctUntilChanged()
//            .flatMapLatest { query -> Observable<[Repository]> in
//                if query.isEmpty {
//                    return .just([])
//                }
//                return searchGitHub(query)
//                    .catchErrorJustReturn([])
//            }
//            .observeOn(MainScheduler.instance)

//        let tt = UITableView()

//        mobilePhone.bind(to: getVerifyCodeButton.rx.isUserInteractionEnabled) {
//            (isUser:Bool) in
//            self.getVerifyCodeButton.isUserInteractionEnabled = isUser
//        }
        
    }
    
    //MARK: - setupUI item detial
    func setupMobilePhoneTextField() -> Void {
        let margin: CGFloat = 40
        let viewHeight: CGFloat = 45
        
        let containerView = UIToolbar(frame: CGRect(x: margin, y: 0, width: self.bounds.size.width - margin - margin, height: viewHeight))
        containerView.layer.cornerRadius = 10
        containerView.layer.borderWidth = 1
        containerView.layer.borderColor = UIColor.purple.cgColor
        containerView.layer.masksToBounds = true
        addSubview(containerView)
        containerView.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(margin)
            make.right.equalToSuperview().offset(-margin)
            make.top.equalToSuperview()
            make.height.equalTo(viewHeight)
        }
        
        containerView.addSubview(getVerifyCodeButton)
        getVerifyCodeButton.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.right.equalToSuperview().offset(-8)
            make.height.equalTo(26)
//            make.width.greaterThanOrEqualTo(20)
            make.width.equalTo(80)
        }
        
        //模拟器上UItextfield加到uitoolbar上无法响应点击,被一层view盖住了
//        addSubview(getVerifyCodeButton)
//        var buttonFrame = containerView.frame
//        buttonFrame.origin.x = (buttonFrame.origin.x + buttonFrame.size.width - 85)
//        buttonFrame.origin.y = buttonFrame.origin.y + 10
//        buttonFrame.size.width = 80
//        buttonFrame.size.height = buttonFrame.size.height - 20
//        getVerifyCodeButton.frame = buttonFrame
        
        
        containerView.insertSubview(mobilePhoneTextField, belowSubview: getVerifyCodeButton)
        mobilePhoneTextField.frame = CGRect(x: 12, y: 0, width: containerView.bounds.size.width - 92, height: viewHeight)
        mobilePhoneTextField.snp.makeConstraints { (make) in
            make.top.bottom.equalToSuperview()
            make.left.equalToSuperview().offset(10)
            make.right.equalTo(getVerifyCodeButton.snp.left).offset(-8)
        }
        
//        addSubview(mobilePhoneTextField)
//        var mobilePTFFrame = containerView.frame
//        mobilePTFFrame.origin.x = mobilePTFFrame.origin.x + 10
//        mobilePTFFrame.size.width = mobilePTFFrame.size.width - 100
//        mobilePhoneTextField.frame = mobilePTFFrame

    }
    
    func setupVerifyCodeTextField() -> Void {
        let margin: CGFloat = 40
        let viewHeight: CGFloat = 45
        
        let containerView = UIToolbar(frame: CGRect(x: margin, y: viewHeight + 20, width: self.bounds.size.width - margin - margin, height: viewHeight))
        containerView.layer.cornerRadius = 10
        containerView.layer.borderWidth = 1
        containerView.layer.borderColor = UIColor.purple.cgColor
        containerView.layer.masksToBounds = true
        
        addSubview(containerView)
        
        containerView.addSubview(verifyCodeTextField)
        verifyCodeTextField.snp.makeConstraints { (make) in
            make.top.bottom.equalToSuperview()
            make.left.equalToSuperview().offset(10)
            make.right.equalToSuperview().offset(-10)
        }
        
//        addSubview(verifyCodeTextField)
//        var verifyCTFFrame = containerView.frame
//        verifyCTFFrame.origin.x = verifyCTFFrame.origin.x + 10
//        verifyCTFFrame.size.width = verifyCTFFrame.size.width - 20
//        verifyCodeTextField.frame = verifyCTFFrame
    }
    
    //MARK: - getter
    lazy var mobilePhoneTextField: UITextField = {
        let tempView = UITextField()
        tempView.font = PPYGlobalConstants.fontLevel2
        tempView.placeholder = "手机号"

        tempView.textColor = UIColor.purple
        tempView.keyboardType = .phonePad
        tempView.text = ""
        return tempView
    }()
    
    lazy var verifyCodeTextField: UITextField = {
        let tempView = UITextField()
        tempView.font = PPYGlobalConstants.fontLevel2
        tempView.placeholder = "验证码"
        tempView.textColor = UIColor.purple
        tempView.keyboardType = .numberPad
        tempView.text = ""
        return tempView
    }()
    
    lazy var getVerifyCodeButton: UIButton = {
        let tempView = UIButton()
        tempView.contentEdgeInsets = UIEdgeInsets(top: 30, left: 0, bottom: 30, right: 0)
        tempView.titleLabel?.font = PPYGlobalConstants.fontLevel3
        
        tempView.setTitleColor(UIColor.white, for: .normal)
        tempView.setTitleColor(UIColor.white.withAlphaComponent(0.4), for: .disabled)
//        tempView.setBackgroundImage(UIImage(named: ""), for: .)
        tempView.backgroundColor = UIColor(red: 174 / 255, green: 85 / 255, blue: 255 / 255, alpha: 1.0)//ColorWithRGB(red: 0, green: 240, blue: 0, alpha: 0.8)
        tempView.setTitle("获取验证码", for: .normal)
        tempView.addTarget(self, action: #selector(getVerifyCodeButtonClicked), for:
            .touchUpInside)
//        tempView.isUserInteractionEnabled = false
        tempView.layer.cornerRadius = 10
        tempView.layer.masksToBounds = true
        return tempView
    }()
    
    lazy var loginButton: UIButton = {
        let tempView = UIButton()
        
        tempView.setTitleColor(UIColor.white.withAlphaComponent(0.4), for: .disabled)
        tempView.setTitleColor(UIColor.white, for: .normal)
        tempView.setTitle("登录", for: .normal)
        
        tempView.backgroundColor = UIColor(red: 174 / 255, green: 85 / 255, blue: 255 / 255, alpha: 1.0)
        
        tempView.layer.cornerRadius = 20
        tempView.layer.masksToBounds = true
        
        
        tempView.addTarget(self, action: #selector(loginButtonClicked), for: .touchUpInside)
        return tempView
    }()
    
    //MARK: - events response
    @objc private func loginButtonClicked() -> Void {
        endEditing(true)
        
//        if !isPhoneNumberValidate() {
//            return
//        }
//
//        if !isPasswordValidate() {
//            return
//        }
//
//        BXPProgressHUD.showLoading()
//
//        if loginWayChangeButton.isSelected {
//            loginViewModel.loginWith(userID: userNameTextField.text!, password: passwordTextField.text!)
//        } else {
//            loginViewModel.loginWith(userID: userNameTextField.text!, verifyCode: passwordTextField.text!)
//        }
        print("--xp--login---")
        
        PPYNetworkTools.ppyRequestTest(["test":"test"]) { (succeed, response, error) in
            print(response)
            if (error != nil) {
                print(error?.localizedDescription)
            }
            if let responseJson = response as? Dictionary<String, Any> {
                if let responseData = responseJson["data"] as? Dictionary<String, Any> {
//                    if let responseDict = responseData["resp"] as? Dictionary<String, Any> {
//
//                    }
                }
                
                if let msg = responseJson["msg"] as? String {
                    let label = UILabel(frame: CGRect(x: 10, y: 10, width: 100, height: 30))
                    label.backgroundColor = UIColor.red
                    label.textColor = UIColor.white
                    label.text = msg
                    self.addSubview(label)
                }
            }
        }
    }
    
    @objc private func getVerifyCodeButtonClicked() -> Void {
        endEditing(true)
        //rxswift 已经做了输入验证,所以一般来说,能点击按钮,应该是手机输入有值才对
        if (mobilePhoneTextField.text?.count)! < 11 {
            MBProgressHUD.showError(message: "请输入有效的验证码")
            return
        }
        if delegate != nil && (delegate?.responds(to: #selector(PPYLoginViewDelegate.getVerifyButtonClicked(mobilePhone:))))! {
            delegate?.getVerifyButtonClicked!(mobilePhone: mobilePhoneTextField.text!)
        }
        
        getVerifyCodeButton.isEnabled = false
        getVerifyCodeButton.backgroundColor = UIColor.gray
//        getVerifyCodeButton.setTitleColor(<#T##color: UIColor?##UIColor?#>, for: <#T##UIControlState#>)
        print("--xp--get-v---")
//        if !isPhoneNumberValidate() {
//            return
//        }
//
//        BXPSMSTools.getVerifyCode(phoneNumber: userNameTextField.text!) { (error) in
//            if error == nil {
//                //                print("--xp--获取验证码成功")
//                BXPProgressHUD.showMessage("验证码获取成功,请查收")
//            } else {
//                BXPProgressHUD.showMessageWithError("获取验证码失败,请稍后重试")
//            }
//        }
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        mobilePhoneTextField.resignFirstResponder()
        verifyCodeTextField.resignFirstResponder()
    }

}


